# coding=UTF-8
import os
import sys
import time
import requests
import json

father_path = os.path.abspath(os.path.dirname(os.getcwd()) + os.path.sep + ".")
sys.path.append(father_path)
from service import data_service


def real_time_price(stock_code, stock_exchange, size):
    time_stamp = int(round(time.time() * 1000))
    path_url = 'http://push2.eastmoney.com/api/qt/stock/details/get?' \
               'ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1,f2,f3,f4&' \
               'fields2=f51,f52,f53,f54,f55&' \
               'pos=-' + str(size) + \
               '&secid=' + str(stock_exchange) + '.' + str(stock_code) + \
               '&cb=jQuery1124011692851191143305_' + str(time_stamp) + '&_=' + str(time_stamp + 103)
    # print(path_url)
    resp = requests.get(path_url)
    resp_content = str(resp.content.decode('utf-8'))
    days_info_str = resp_content.split('(')[1].split(')')[0]
    resp_json = json.loads(days_info_str)
    return resp_json['data']['details']


# 分_k 价格
def minutes_k(stock_code, stock_exchange, days):
    time_stamp = int(round(time.time() * 1000))
    # 实时价格url
    path_url = 'http://push2.eastmoney.com/api/qt/stock/trends2/get?' + \
               'fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13' + \
               '&fields2=f51,f52,f53,f54,f55,f56,f57,f58' + \
               '&ut=fa5fd1943c7b386f172d6893dbfba10b&ndays=' + str(days) + \
               '&iscr=0&' \
               'secid=' + str(stock_exchange) + '.' + str(stock_code) + \
               '&cb=jQuery1124030062123329295565_' + \
               str(time_stamp) + '&_=' + str(time_stamp + 41)
    resp = requests.get(path_url)
    resp_content = str(resp.content.decode('utf-8'))
    days_info_str = resp_content.split('(')[1].split(')')[0]
    resp_json = json.loads(days_info_str)
    return resp_json['data']['trends']


#  获取实时价格
def get_rt_p(stock_code):
    dict = data_service.stock(stock_code)
    details = real_time_price(stock_code, dict['exchange'], 1)
    if len(details) == 0:
        return 0
    return float(details[0].split(',')[1])


# 获取含有长度的价格
def get_rt_ps(stock_code, size):
    dict = data_service.stock(stock_code)
    return real_time_price(stock_code, dict['exchange'], size)


if __name__ == '__main__':
    print(get_rt_p('002594'))
